//
//  OrderChatTableViewCell.swift
//  Exchange
//
//  Created by rui on 2018/5/8.
//  Copyright © 2018年 common. All rights reserved.
//

import UIKit

protocol OrderChatCellDelegate: class {
    func OrderChatArrowClick(btn: UIButton)
    func OrderChatLeftClick(status: ChatButtonStatus)
    func OrderChatRightClick(status: ChatButtonStatus)
    func OrderChatSureClick(isEdit: Bool)
}

class ExchangeChatNoOrderHeaderView: UIView {
    weak var delegate: OrderChatCellDelegate?
    
    var model: WaitOrderDetailModel? {
        didSet {
            self.configer()
        }
    }
    
    var containerView: UIView = {
        let container = UIView()
        container.themeBackground = ThemeManager.ThemeColorKeys.background
        container.layer.cornerRadius = 5
        container.layer.masksToBounds = true
        return container
    }()
    
    lazy var sureBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle(kText("--"), for: .normal)
        btn.setTitleColor(UIColor(hexStr: "#fdfdfd"), for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.layer.cornerRadius = 3
        btn.layer.backgroundColor = kThemeColor.cgColor
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(sureClick(btn:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var price: UILabel = {
        let lbl = UILabel()
        lbl.themeTextColor = ThemeManager.ThemeColorKeys.text1
        lbl.textAlignment = .left
        lbl.font = UIFont.systemFont(ofSize: 14)
        lbl.text = kText("报价")+": --CNY"
        return lbl
    }()
    
    lazy var limit: UILabel = {
        let lbl = UILabel()
        lbl.themeTextColor = ThemeManager.ThemeColorKeys.text2
        lbl.textAlignment = .left
        lbl.font = UIFont.systemFont(ofSize: 13)
        lbl.text = kText("限额")+": --CNY"
        return lbl
    }()

    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI() {
        self.addSubview(containerView)
        containerView.addSubview(price)
        containerView.addSubview(limit)
        containerView.addSubview(sureBtn)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        let leftRightMargin: CGFloat = 16
        let topMargin: CGFloat = 12
        containerView.frame = CGRect(x: leftRightMargin, y: topMargin, width: self.width - leftRightMargin * 2 , height: self.height - topMargin * 2)
        price.frame = CGRect(x: leftRightMargin, y: leftRightMargin, width: containerView.width - leftRightMargin * 2, height: 22)
        limit.frame = CGRect(x: leftRightMargin, y: price.bottom + 5, width: price.width, height: 20)
        sureBtn.width = 100
        sureBtn.height = 35
        sureBtn.x = containerView.width - sureBtn.width - leftRightMargin
        sureBtn.centerY = containerView.height * 0.5
    }
    
    @objc func sureClick(btn: UIButton) {
        var isEdit = false
        if btn.title(for: .normal) == kText("编辑广告") {
            isEdit = true
        }
        self.delegate?.OrderChatSureClick(isEdit: isEdit)
    }
    
    private func configer() {
        guard let model = self.model else { return }
        let currency = model.currency ?? ""
        
        let lower = model.limitLowerMoney ?? 0
        let upper = model.limitUpperMoney ?? 0
        self.limit.text = String(format: "%@:%0.2f-%0.2f%@", kText("限额"),lower,upper,currency)
        
        var price = AppContext.default.getExTick(symbol: model.moneyType ?? "", currency: currency)
        price = price + price * (model.premium ?? 0) / 100
        self.price.text = String(format: "%0.2lf %@", price,currency)
        
        ///发广告者是自己
        if model.userId == AppInfo.default.userId {
            self.sureBtn.setTitle(kText("编辑广告"), for: .normal)
        }else {
            if model.type == 0 {
                self.sureBtn.setTitle(kText("立即出售"), for: .normal)
            }else {
                self.sureBtn.setTitle(kText("立即购买"), for: .normal)
            }
            
        }
    }

}


enum ChatButtonStatus {
    case cancel //取消订单
    case appeal //申诉
    case canceled //已取消
    case markPayed //标记付款
    case releseCoin //释放币种
    case notifyReleseCoin //通知释放币
    case evaluate ///评价
    case wallet //查看钱包
    case unkown
}

class ExchangeChatHeaderView: UIView {
    
    weak var delegate: OrderChatCellDelegate?
    
    var model: TradeOrderListModel? {
        didSet {
            self.configer()
        }
    }
    
    var leftBtnStatus: ChatButtonStatus = .unkown
    
    var rightBtnStatus: ChatButtonStatus = .unkown

    var containerView: UIView = {
        let container = UIView()
        container.themeBackground = ThemeManager.ThemeColorKeys.background
        container.layer.cornerRadius = 5
        container.layer.masksToBounds = true
        return container
    }()
    
    var isUnfold: Bool = false {
        didSet{
            setNeedsLayout()
            layoutIfNeeded()
            UIView.animate(withDuration: 0.25) {
                if self.isUnfold {
                    self.arrowBtn.transform = CGAffineTransform(rotationAngle: CGFloat.pi)
                }else {
                    self.arrowBtn.transform = CGAffineTransform.identity
                }
            }
        }
    }
    
    lazy var orderNum: UILabel = {
        return createLabel(title: kText("订单编号") + ":--")
    }()
    ///支付状态
    lazy var payState: UILabel = {
        let lbl = UILabel()
        lbl.text = kText("等待支付")
        lbl.font = UIFont.systemFont(ofSize: 14)
        lbl.textAlignment = .right
        lbl.sizeToFit()
        lbl.textColor = UIColor.red
        return lbl
    }()
    
    lazy var exchangeMoneyTitle: UILabel = {
        return createLabel(title: kText("交易金额"))
    }()
    ///交易金额
    lazy var exchangeMoney: UILabel = {
        let lbl = createLabel(title: "--")
        lbl.textAlignment = .right
        return lbl
    }()
    
    lazy var exchangeAccountTitle: UILabel = {
        return createLabel(title: kText("交易数量"))
    }()
    ///交易数量
    lazy var exchangeAccount: UILabel = {
        let lbl = createLabel(title: "--")
        lbl.textAlignment = .right
        return lbl
    }()
    
    lazy var exchangePriceTitle: UILabel = {
        return createLabel(title: kText("交易价格"))
    }()
    
    ///交易价格
    lazy var exchangePrice: UILabel = {
        let lbl = createLabel(title: "--")
        lbl.textAlignment = .right
        return lbl
    }()
    
    lazy var exchangeTimeTitle: UILabel = {
        return createLabel(title: kText("下单时间"))
    }()
    ///下单时间
    lazy var exchangeTime: UILabel = {
        let lbl = createLabel(title: "--")
        lbl.textAlignment = .right
        return lbl
    }()
    ///卖家
    lazy var seller: UILabel = {
        let lbl = createLabel(title: kText("卖家") + ":lingsd-btc")
        lbl.textAlignment = .left
        return lbl
    }()
    
    //支付方式
    lazy var payType: UIImageView = {
        let lbl = UIImageView()
        return lbl
    }()
    ///买家
    lazy var buyer: UILabel = {
        let lbl = createLabel(title: kText("买家") + ":lingsd-btc")
        lbl.textAlignment = .right
        return lbl
    }()
    
    ///留言
    lazy var leaveMessage: UILabel = {
        let lbl = createLabel(title: kText("广告留言") + ":支付宝转账")
        lbl.numberOfLines = 0
        lbl.sizeToFit()
        return lbl
    }()
    
    lazy var tip: UILabel = {
        let lbl = UILabel()
        lbl.text = kText("--")
        lbl.numberOfLines = 0
        lbl.sizeToFit()
        lbl.font = UIFont.systemFont(ofSize: 12)
        lbl.textAlignment = .center
        lbl.themeTextColor = ThemeManager.ThemeColorKeys.text2
        lbl.sizeToFit()
        return lbl
    }()
    
    lazy var cancelBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle(kText("取消交易"), for: .normal)
        btn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text2, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.layer.cornerRadius = 3
        btn.layer.border = ThemeManager.ThemeColorKeys.text2
        btn.layer.borderWidth = 0.5
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(cancelClick(btn:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var sureBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle(kText("标记付款"), for: .normal)
        btn.setTitleColor(kThemeColor, for: .normal)
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.layer.cornerRadius = 3
        btn.layer.borderColor = kThemeColor.cgColor
        btn.layer.borderWidth = 0.5
        btn.layer.masksToBounds = true
        btn.addTarget(self, action: #selector(sureClick(btn:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var arrowBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(#imageLiteral(resourceName: "arrow_down"), for: .normal)
        btn.addTarget(self, action: #selector(arrowClick(btn:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var line1: UIView = {
        return createLine()
    }()
    
    lazy var line2: UIView = {
        return createLine()
    }()
    
    lazy var line3: UIView = {
        return createLine()
    }()
    
    lazy var copyBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.contentEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3)
        btn.themeSetImage(ThemeManager.ThemeImageKeys.tradeCopy, for: .normal)
        btn.addTarget(self, action: #selector(copyOrder(btn:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var copyPriceBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.contentEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3)
        btn.themeSetImage(ThemeManager.ThemeImageKeys.tradeCopy, for: .normal)
        btn.addTarget(self, action: #selector(copyOrder(btn:)), for: .touchUpInside)
        return btn
    }()
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        exchangeAccount.isHidden = !isUnfold
        exchangeAccountTitle.isHidden = !isUnfold
        exchangePriceTitle.isHidden = !isUnfold
        exchangePrice.isHidden = !isUnfold
        exchangeTimeTitle.isHidden = !isUnfold
        exchangeTime.isHidden = !isUnfold
        seller.isHidden = !isUnfold
        buyer.isHidden = !isUnfold
        payType.isHidden = !isUnfold
        leaveMessage.isHidden = !isUnfold
        line2.isHidden = !isUnfold
        
        let leftRightMargin: CGFloat = 16
        let topBottomMargin: CGFloat = 12
        
        self.containerView.frame = CGRect(x: leftRightMargin, y: topBottomMargin, width: self.width - leftRightMargin * 2.0, height: self.height - topBottomMargin * 2.0)
        orderNum.sizeToFit()
        orderNum.x = leftRightMargin
        orderNum.y = leftRightMargin
        
        copyBtn.x = orderNum.right + 5
        copyBtn.centerY = orderNum.centerY
        copyBtn.width = 20
        copyBtn.height = 20
        
        payState.sizeToFit()
        payState.right = containerView.width - leftRightMargin
        payState.y = leftRightMargin
        
        line1.frame = CGRect(x: leftRightMargin, y: orderNum.bottom + topBottomMargin, width: containerView.width - leftRightMargin * 2.0, height: 0.5)
        
        exchangeMoneyTitle.sizeToFit()
        exchangeMoneyTitle.x = leftRightMargin
        exchangeMoneyTitle.y = line1.bottom + topBottomMargin
        exchangeMoney.sizeToFit()
        exchangeMoney.right = payState.right
        exchangeMoney.y = exchangeMoneyTitle.y
        
        copyPriceBtn.right = exchangeMoney.x - 4
        copyPriceBtn.centerY = exchangeMoneyTitle.centerY
        copyPriceBtn.width = 20
        copyPriceBtn.height = 20
        
        exchangeAccountTitle.sizeToFit()
        exchangeAccountTitle.x = leftRightMargin
        exchangeAccountTitle.y = exchangeMoneyTitle.bottom + topBottomMargin
        
        exchangeAccount.sizeToFit()
        exchangeAccount.right = payState.right
        exchangeAccount.y = exchangeAccountTitle.y
        
        exchangePriceTitle.sizeToFit()
        exchangePriceTitle.x = leftRightMargin
        exchangePriceTitle.y = exchangeAccountTitle.bottom + topBottomMargin
        
        exchangePrice.sizeToFit()
        exchangePrice.right = payState.right
        exchangePrice.y = exchangePriceTitle.y
        
        exchangeTimeTitle.sizeToFit()
        exchangeTimeTitle.x = leftRightMargin
        exchangeTimeTitle.y = exchangePriceTitle.bottom + topBottomMargin
        
        exchangeTime.sizeToFit()
        exchangeTime.right = payState.right
        exchangeTime.y = exchangeTimeTitle.y
        
        line2.frame = CGRect(x: leftRightMargin, y: exchangeTime.bottom + topBottomMargin, width: containerView.width - leftRightMargin * 2.0, height: 0.5)
        
        seller.sizeToFit()
        seller.height = 20
        if seller.width >= self.containerView.width * 0.5 - 16 - 20  {
            seller.width = self.containerView.width * 0.5 - 16 - 20
        }
        seller.x = leftRightMargin
        seller.y = line2.bottom + topBottomMargin
        
        payType.width = 15
        payType.height = 15
        payType.x = seller.right + 2
        payType.centerY = seller.centerY
        
        buyer.height = 20
        buyer.width = self.containerView.width * 0.5 - 16
        buyer.right = payState.right
        buyer.y = seller.y
        
        leaveMessage.width = containerView.width - 2.0 * leftRightMargin
        leaveMessage.sizeToFit()
        leaveMessage.x = leftRightMargin
        leaveMessage.y = seller.bottom + topBottomMargin
        
        
        line3.x = leftRightMargin
        if self.isUnfold {
            line3.y = leaveMessage.bottom + topBottomMargin
        }else {
            line3.y = exchangeMoneyTitle.bottom + topBottomMargin
        }
        line3.width = containerView.width - 2 * leftRightMargin
        line3.height = 0.5

        tip.sizeToFit()
        tip.width = line3.width
        tip.x = leftRightMargin
        tip.y = line3.bottom + topBottomMargin
        
        
        let w = (containerView.width - leftRightMargin * 2.0 -  25.0) * 0.5
        cancelBtn.x = leftRightMargin
        cancelBtn.y = tip.bottom + topBottomMargin
        cancelBtn.width = w
        cancelBtn.height = 35
        
        if sureBtn.isHidden {
            cancelBtn.centerX = containerView.width * 0.5
        }
        
        
        
        sureBtn.width = w
        sureBtn.height = 35
        sureBtn.right = payState.right
        sureBtn.y = cancelBtn.y
        
        if cancelBtn.isHidden {
            sureBtn.centerX = containerView.width * 0.5
        }
        
        arrowBtn.width = 44
        arrowBtn.height = 15
        arrowBtn.y = sureBtn.bottom + topBottomMargin
        arrowBtn.x = (containerView.width - 44) * 0.5
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        initUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func initUI() {
        self.addSubview(containerView)
        containerView.addSubview(orderNum)
        containerView.addSubview(copyBtn)
        containerView.addSubview(copyPriceBtn)
        containerView.addSubview(payState)
        containerView.addSubview(exchangeMoneyTitle)
        containerView.addSubview(exchangeMoney)
        containerView.addSubview(exchangeAccountTitle)
        containerView.addSubview(exchangeAccount)
        containerView.addSubview(exchangePriceTitle)
        containerView.addSubview(exchangePrice)
        containerView.addSubview(exchangeTimeTitle)
        containerView.addSubview(exchangeTime)
        containerView.addSubview(seller)
        containerView.addSubview(buyer)
        containerView.addSubview(payType)
        containerView.addSubview(leaveMessage)
        containerView.addSubview(tip)
        containerView.addSubview(cancelBtn)
        containerView.addSubview(sureBtn)
        containerView.addSubview(arrowBtn)
        
        containerView.addSubview(line1)
        containerView.addSubview(line2)
        containerView.addSubview(line3)
    }
    
    
    private func createLabel(title: String?) -> UILabel {
        let lbl = UILabel()
        lbl.themeTextColor = ThemeManager.ThemeColorKeys.text1
        lbl.textAlignment = .left
        lbl.font = UIFont.systemFont(ofSize: 14)
        lbl.text = title
        return lbl
    }
    
    private func createLine() -> UIView {
        let line = UIView()
        line.themeBackground = ThemeManager.ThemeColorKeys.separator
        return line
    }
    
    @objc func arrowClick(btn: UIButton) {
        self.isUnfold = !self.isUnfold
        self.delegate?.OrderChatArrowClick(btn: btn)
    }
    
    @objc func cancelClick(btn: UIButton) {
        self.delegate?.OrderChatLeftClick(status: self.leftBtnStatus)
    }
    @objc func sureClick(btn: UIButton) {
        self.delegate?.OrderChatRightClick(status: self.rightBtnStatus)
    }
    
    @objc func copyOrder(btn: UIButton) {
        let pasteboard = UIPasteboard.general
        if btn == self.copyBtn {
            let strArray = self.orderNum.text?.components(separatedBy: ":")
            pasteboard.string = strArray?.last ?? ""
            CYMBShow.showMessage(kText("复制订单号成功"))
        }else if btn == self.copyPriceBtn {
            let currency = model?.currency ?? ""
            var price = self.exchangeMoney.text ?? ""
            let range = price.range(of: currency)
            price.removeSubrange(range!)
            pasteboard.string = price
            CYMBShow.showMessage(kText("复制交易金额成功"))
        }
    }
    
    private func configer() {
        guard let model = self.model else { return }
        
        let isBuyer = (AppInfo.default.userId ?? 0) == (model.buyer ?? 0)
        var canAppeal = false
        if let timeStr = model.payConfirmTime {
            let df = DateFormatter()
            df.dateFormat = "yyyy-MM-dd HH:mm:ss"
            df.timeZone = TimeZone(identifier: "Asia/Shanghai")
            let date = df.date(from: timeStr)
            let pay = date?.timeIntervalSince1970
            let now = Date().timeIntervalSince1970
            if isBuyer {
                if (now - pay! > 60 * 30) {
                    canAppeal = true
                }
            }else {
                canAppeal = true
            }
        }

        orderNum.text = kText("订单号") + ":" + (model.number ?? "--")
        payState.text = model.getState()
        
        let currency = model.currency ?? ""
        
        self.exchangeMoney.text = String(format: "%0.2f%@", model.amount ?? 0,currency)
        let coinModel = AppContext.default.loadTradeCoinPrecision(coinCode: model.moneyType ?? "")
        self.exchangeAccount.text =  String(format: "%@",
                                           CYCalculate.cy_intercept(number: (model.quantity ?? 0), digit: coinModel?.coinPrecision ?? 8,isCover: true)!) + (model.moneyType ?? "")
        self.exchangePrice.text = String(format: "%0.2f%@", model.unitPrice ?? 0,currency)
        
        
        
        self.exchangeTime.text = model.createdAt
        
        self.seller.text = String(format: "%@:%@", kText("卖家"),model.sellName ?? "")
        self.buyer.text = String(format: "%@:%@", kText("买家"),model.buyerName ?? "")
        
        if model.payMethod == 2 {
            payType.image = #imageLiteral(resourceName: "unionPay")
        }else {
            payType.image = #imageLiteral(resourceName: "aliPay")
        }
        self.tip.text = model.getStateText()
        self.leaveMessage.text = kText("广告留言") + ":" + (model.message ?? "--")
        let payStatus = model.payStatus ?? 0
        let status = model.status ?? 0
        
        let isEvaluate = model.isEvaluate ?? 0
        
        //左边按钮
         self.cancelBtn.isHidden = false
        self.leftBtnStatus = .unkown
        if (payStatus == 2 || (payStatus == 0 && !isBuyer)) || (status == 1 && (payStatus ==  1 || payStatus == 0)) {
            //左边没有按钮
            self.cancelBtn.isHidden = true
        }else {
            if isBuyer {
                if model.isAppeal != 1 {
                    self.leftBtnStatus = .cancel
                    self.cancelBtn.setTitle(kText("取消交易"), for: .normal)
                }else {
                    self.cancelBtn.isHidden = true
                }
            }else {
                self.leftBtnStatus = .appeal
                self.cancelBtn.setTitle(kText("申诉"), for: .normal)
            }
        }
        
        //右边按钮
        self.sureBtn.isHidden = false
        self.sureBtn.setTitleColor(kThemeColor, for: .normal)
        self.sureBtn.layer.borderColor = kThemeColor.cgColor
        self.rightBtnStatus = .unkown
        if status == 1 && (payStatus == 0 || payStatus == 1) {
            self.sureBtn.themeSetTitleColor(ThemeManager.ThemeColorKeys.text2, for: .normal)
            self.sureBtn.layer.border = ThemeManager.ThemeColorKeys.text2
            self.rightBtnStatus = .canceled
            self.sureBtn.setTitle(kText("交易已取消"), for: .normal)
        }else if payStatus == 0 {
            if isBuyer {
                self.rightBtnStatus = .markPayed
                self.sureBtn.setTitle(kText("标记付款"), for: .normal)
            }else {
                self.rightBtnStatus = .releseCoin
                var text = kText("释放")
                if AppCacheInfo.default.isEnlish {
                    text = text + " "
                }
                self.sureBtn.setTitle(text + (model.moneyType ?? ""), for: .normal)
            }
        }else if payStatus == 1 {
            
            if isBuyer {
                if canAppeal {
                    self.rightBtnStatus = .appeal
                    self.sureBtn.setTitle(kText("申诉"), for: .normal)
                }else {
                    self.rightBtnStatus = .notifyReleseCoin
                    self.sureBtn.setTitle(kText("提醒卖家"), for: .normal)
                }
            }else {
                self.rightBtnStatus = .releseCoin
                var text = kText("释放")
                if AppCacheInfo.default.isEnlish {
                    text = text + " "
                }
                self.sureBtn.setTitle(text + (model.moneyType ?? ""), for: .normal)
            }
        }else {
            if isEvaluate == 0 || (isEvaluate == 1 && !isBuyer) || (isEvaluate == 2 && isBuyer)  {
                self.rightBtnStatus = .evaluate

                self.sureBtn.setTitle(kText("评价"), for: .normal)
            }else if (isBuyer &&  isEvaluate == 1)||(!isBuyer && isEvaluate == 2) || isEvaluate == 3 {
                self.rightBtnStatus = .wallet
                 self.sureBtn.setTitle(kText("查看钱包"), for: .normal)
            }else {
                self.rightBtnStatus = .unkown

                self.sureBtn.isHidden = true
            }
        }
        self.setNeedsLayout()
        self.layoutIfNeeded()
        self.delegate?.OrderChatArrowClick(btn: self.arrowBtn)
    }

}
